// components/play-sound/index.js
Component({
  /**
   * 组件的属性列表
   */
  properties: {
    duration:{
      type:Number,
      value:5200,
      observer(){
        let {duration,viewsHeight} = this.data
        const time = duration/13
        viewsHeight.forEach((item,index)=>{
          item.time = duration - time*(index+1)
        })
        this.setData({
          viewsHeight
        })
      }
    },
    url:{
      type:String,
    },
  },

  /**
   * 组件的初始数据
   */
  data: {
    isPlay:false,// 是否正在播放
    remainderDuration:5200,// 播放时间
    viewsHeight:[
      {height:20,time:""},
      {height:24,time:""},
      {height:44,time:""},
      {height:20,time:""},
      {height:24,time:""},
      {height:45,time:""},
      {height:20,time:""},
      {height:40,time:""},
      {height:30,time:""},
      {height:24,time:""},
      {height:40,time:""},
      {height:33,time:""},
      {height:23,time:""},
    ]
  },
  lifetimes:{
    attached(){
      // this.viewsHeight()
      this.innerAudioContext = wx.createInnerAudioContext()
      // 监听开始播放
      this.innerAudioContext.onPlay(() => {
        this.timer = setInterval(()=>{
          const {remainderDuration} = this.data
          remainderDuration = remainderDuration - 1000
          this.setData({
            remainderDuration:remainderDuration<=0?0:remainderDuration
          })
        },500)
        this.setData({
          isPlay:true
        })
      })
      // 监听听停止播放(事件中断)
      this.innerAudioContext.onStop(() => {
        clearInterval(this.timer)
        this.setData({
          isPlay:false,
          remainderDuration:this.data.duration
        })
      })
      // 监听播放结束(自然结束)
      this.innerAudioContext.onEnded(() => {
        clearInterval(this.timer)
        this.setData({
          isPlay: false,
          remainderDuration:this.data.duration
        })
      })
    }
  },
  /**
   * 组件的方法列表
   */
  methods: {
    play(){
      const {isPlay,url} = this.data
      // 正在播放就停止，没有播放就播放
      if(isPlay){
        this.innerAudioContext.stop()
      }else{
        this.innerAudioContext.autoplay = true
        this.innerAudioContext.src = url
      }
      // this.setData({
      //   isPlay:!isPlay
      // })
      // let {isPlay,remainderDuration,duration,viewsHeight} = this.data
      // if(!isPlay){

      //   this.timer = setInterval(()=>{
      //     remainderDuration = remainderDuration - 1000
      //     this.setData({
      //       remainderDuration
      //     })
      //   },500)
      // }else{
      //   clearInterval(this.timer)
      //   remainderDuration = duration
      // }
      // this.setData({
      //   isPlay:!isPlay,
      //   remainderDuration,
      //   viewsHeight
      // })
    },
  }
})
